package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        // 该集合用于存放begin到end范围内的全部日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 将begin到end范围内的全部日期加入到集合中
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);// 日期计算，获得指定日期后一天的日期
            dateList.add(begin);
        }

        // 存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // select sum(amount) from orders where order_time >= beginTime and order_time <= endTime and status = 5
            // 查询date日期对应的营业额数据，营业额是指状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);// date日期的开始时刻
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);// date日期的结束时刻
            // 将条件（status、beginTime、endTime）封装到map
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);// 状态为已完成
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);// 计算出当天的营业额
            turnover = turnover == null ? 0.0 : turnover;// 当天没有订单需要将营业额转成0
            turnoverList.add(turnover);// 将当天的营业额加入集合
        }

        // 数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))// 将dataList的所有元素转为字符串，元素之间用,分隔
                .turnoverList(StringUtils.join(turnoverList, ","))// 将turnoverList所有元素转为字符串，元素之间用,分隔
                .build();
    }

    /**
     * 根据时间区间统计用户数据
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 存放begin到end之间的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存放每天新增的用户数
        List<Integer> newUserList = new ArrayList<>();
        // 存放每天总用户数
        List<Integer> totalUserList = new ArrayList<>();

        // 遍历每一天
        for (LocalDate date : dateList) {
            // date日期的开始时刻
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // date日期的结束时刻
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 新用户数
            // select count(id) from user where create_time >= beginTime and create_time <= endTime
            Integer newUser = getUserCount(beginTime, endTime);
            // 总用户数
            // select count(id) from user where create_time <= end_time
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        // 封装结果数据
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))// 日期字符串
                .newUserList(StringUtils.join(newUserList, ","))// 新用户数字符串
                .totalUserList(StringUtils.join(totalUserList, ","))// 总用户数字符串
                .build();

    }

    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    /**
     * 根据时间区间统计订单数据
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 存放begin到end之间的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        // 每天有效订单总数集合
        List<Integer> vaildOrderCountList = new ArrayList<>();

        // 遍历时间区间内的每一天，查询每天的订单总数和有效订单数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 查询每天的总订单数
            // select count(id) from orders where create_time >= beginTime and create_time <= endTime
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            // 查询每天的有效订单总数
            // select count(id) from orders where create_time >= beginTime and create_time <= endTime and status = 5
            Integer vailOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            vaildOrderCountList.add(vailOrderCount);
        }

        // 时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        // 时间区间内的总有效订单数
        Integer vailOrderCount = vaildOrderCountList.stream().reduce(Integer::sum).get();
        // 订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = vailOrderCount.doubleValue() / totalOrderCount;
        }

        // 返回数据
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(vaildOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(vailOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据时间区间统计指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        // 封装返回数据
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出近30天的运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);// 获得今天往前30天的日期
        LocalDate end = LocalDate.now().minusDays(1);// 获得今天往前1天的日期

        // 查询概览运营数据，提供给Excel模版文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        // 读取Excel模版文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 基于提供好的模版文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            // 获得第4行
            XSSFRow row = sheet.getRow(3);
            // 获取单元格，填充数据
            row.getCell(2).setCellValue(businessData.getTurnover());// 营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());// 订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());// 新增用户数

            // 获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());// 有效订单数
            row.getCell(4).setCellValue(businessData.getUnitPrice());// 平均客单价

            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);// 遍历每一天
                // 准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                // 获取第7 + i行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());// 日期
                row.getCell(2).setCellValue(businessData.getTurnover());// 营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount());// 有效订单
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());// 订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice());// 平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers());// 新增用户数
            }

            // 通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 关闭资源
            out.flush();
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
